package com.lcf.framework.query;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：实体字段映射数据库字段工具类
 *
 * @author lcf
 * @since 2025/2/28 12:46
 */
public class FieldMapper {
    private static final Map<Class<?>, Map<String, String>> FIELD_MAP_CACHE = new HashMap<>();

    public static String getDatabaseFieldName(Class<?> entityClass, String entityFieldName) {
        Map<String, String> fieldMap = FIELD_MAP_CACHE.computeIfAbsent(entityClass, FieldMapper::buildFieldMap);
        return fieldMap.getOrDefault(entityFieldName, entityFieldName);
    }

    private static Map<String, String> buildFieldMap(Class<?> entityClass) {
        Map<String, String> fieldMap = new HashMap<>();
        Field[] fields = ReflectionKit.getFieldList(entityClass).toArray(new Field[0]);
        for (Field field : fields) {
            TableField tableField = field.getAnnotation(TableField.class);
            if (tableField != null && StringUtils.isNotBlank(tableField.value())) {
                fieldMap.put(field.getName(), tableField.value());
            } else {
                fieldMap.put(field.getName(), camelToUnderline(field.getName()));
            }
        }
        return fieldMap;
    }

    private static String camelToUnderline(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (Character.isUpperCase(c)) {
                sb.append("_");
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }
}
